package org.arpit.masteringextjs.rs;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.arpit.masteringextjs.dao.impl.UserDAOImpl;
import org.arpit.masteringextjs.domain.Groups;
import org.arpit.masteringextjs.domain.User;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

@Path("/json/user")
public class UserResource {

	@POST
	@Path("/login")
	@Produces(MediaType.APPLICATION_JSON)
	public String findById(@FormParam("user") String user,
			@FormParam("password") String password) {
		System.out.println(user + ">>>>>>>>>>>>>>>>" + password);
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "{success : true}";
	}

	@GET
	@Path("/logout")
	@Produces(MediaType.APPLICATION_JSON)
	public String logout() {
		System.out.println("Inside logout!!");
		return "{success : true}";
	}

	@GET
	@Path("/findAll")
	@Produces(MediaType.APPLICATION_JSON)
	public String findAll() throws JsonGenerationException,
			JsonMappingException, IOException {
		System.out.println("Inside findAll!!");
		List<User> users = UserDAOImpl.getInstance().findAll();

		ObjectMapper mapper = new ObjectMapper();
		String json = "";

		Map<String, Object> map = new HashMap<>();
		map.put("success", true);
		map.put("data", users);

		// convert map to JSON string
		json = mapper.defaultPrettyPrintingWriter().writeValueAsString(map);
		//System.out.println(json);
		return json;
	}

	public static void main(String[] args) {
		
	}

	public static byte[] extractBytes(String ImageName) throws IOException {
		// open image
		File imgPath = new File(ImageName);
		BufferedImage bufferedImage = ImageIO.read(imgPath);

		// get DataBufferBytes from Raster
		WritableRaster raster = bufferedImage.getRaster();
		DataBufferByte data = (DataBufferByte) raster.getDataBuffer();

		return (data.getData());
	}

	@POST
	@Path("/create")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	public String createUser(
			@FormDataParam("id") String id,
			@FormDataParam("userName") String userName,
			@FormDataParam("name") String name,
			@FormDataParam("email") String email,
			@FormDataParam("group_id") String groupId,
			@FormDataParam("picture") InputStream fileInputStream,
			@FormDataParam("picture") FormDataContentDisposition contentDispositionHeader) {
		
		String uploadedFileLocation = "E://Dev/MasteringEXTJS_WS/masteringextjs/src/main/webapp/resources/profileImages/" + contentDispositionHeader.getFileName();
		 
		System.out.println("Uploaded file location : "+uploadedFileLocation);
		// save it
		//writeToFile(fileInputStream, uploadedFileLocation);
		
		final User user = new User();
		user.setEmail(email);
		user.setName(name);
		user.setUserName(userName);
		//user.setPicture(contentDispositionHeader.getFileName());
		
		Groups groups = new Groups();
		groups.setId(1L);
		user.setGroups(groups);
		
		Long userId = null;
		try{
			userId = Long.parseLong(id);
		} catch (NumberFormatException nfe) {
			//nfe.printStackTrace();
		}
		
		if(userId == null || userId == 0){
			UserDAOImpl.getInstance().create(user);	
		} else {
			user.setId(userId);
			UserDAOImpl.getInstance().update(user);
		}
		return "{success : true}";
	}

	// save uploaded file to new location
	private void writeToFile(InputStream uploadedInputStream,
			String uploadedFileLocation) {

		try {
			OutputStream out = new FileOutputStream(new File(
					uploadedFileLocation));
			int read = 0;
			byte[] bytes = new byte[1024];

			out = new FileOutputStream(new File(uploadedFileLocation));
			while ((read = uploadedInputStream.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}
			out.flush();
			out.close();
		} catch (IOException e) {

			e.printStackTrace();
		}

	}
	
	@POST
	@Path("/delete")
	@Produces(MediaType.APPLICATION_JSON)
	public String deleteUser(@FormParam("id") Long id) {
		UserDAOImpl.getInstance().delete(id);
		return "{success : true}";
	}
}
